<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  
  <title>基本计算器 | Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="刷题记录">
<meta property="og:type" content="article">
<meta property="og:title" content="基本计算器">
<meta property="og:url" content="http://example.com/2021/03/13/224.%E5%9F%BA%E6%9C%AC%E8%AE%A1%E7%AE%97%E5%99%A8/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="刷题记录">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2021-03-13T14:10:58.566Z">
<meta property="article:modified_time" content="2021-03-13T14:22:40.306Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="学习笔记">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="shortcut icon" href="/favicon.png">
  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeface-source-code-pro@0.0.71/index.min.css">

  
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/fancybox/jquery.fancybox.min.css">

  
<meta name="generator" content="Hexo 5.4.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://example.com"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-224.基本计算器" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/2021/03/13/224.%E5%9F%BA%E6%9C%AC%E8%AE%A1%E7%AE%97%E5%99%A8/" class="article-date">
  <time class="dt-published" datetime="2021-03-13T14:10:58.566Z" itemprop="datePublished">2021-03-13</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/leetcode/">leetcode</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="p-name article-title" itemprop="headline name">
      基本计算器
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <h3 id="224-基本计算器"><a href="#224-基本计算器" class="headerlink" title="224.基本计算器"></a>224.基本计算器</h3><h4 id="题目描述"><a href="#题目描述" class="headerlink" title="题目描述"></a>题目描述</h4><p>实现一个基本的计算器来计算一个简单的字符串表达式 s 的值。</p>
<h5 id="示例-1："><a href="#示例-1：" class="headerlink" title="示例 1："></a>示例 1：</h5><blockquote>
<p>输入：s = “1 + 1”<br>输出：2</p>
</blockquote>
<h5 id="示例-2："><a href="#示例-2：" class="headerlink" title="示例 2："></a>示例 2：</h5><blockquote>
<p>输入：s = “ 2-1 + 2 “<br>输出：3</p>
</blockquote>
<h5 id="示例-3："><a href="#示例-3：" class="headerlink" title="示例 3："></a>示例 3：</h5><blockquote>
<p>输入：s = “(1+(4+5+2)-3)+(6+8)”<br>输出：23</p>
</blockquote>
<h5 id="提示："><a href="#提示：" class="headerlink" title="提示："></a>提示：</h5><ul>
<li><code>1 &lt;= s.length &lt;= 3 * 105</code></li>
<li><code>s</code> 由数字、<code>&#39;+&#39;</code>、<code>&#39;-&#39;</code>、<code>&#39;(&#39;</code>、<code>&#39;)&#39;</code>、和 <code>&#39; &#39; </code>组成</li>
<li><code>s</code> 表示一个有效的表达式</li>
</ul>
<h4 id="解题思路-amp-踩坑记录"><a href="#解题思路-amp-踩坑记录" class="headerlink" title="解题思路&amp;踩坑记录"></a>解题思路&amp;踩坑记录</h4><h5 id="踩坑1-一定要读清题"><a href="#踩坑1-一定要读清题" class="headerlink" title="踩坑1 一定要读清题"></a>踩坑1 一定要读清题</h5><p>我一开始以为这是要写一个计算器的程序，实现加减乘除的功能，所以把重点放在怎么拆分字符串，并保留加减乘除的分隔符上了，稍微记录一下，用正则表达式<code>re.split()</code>可以添加多个分隔符并决定是否保留某些分隔符。</p>
<h5 id="解题思路1-消去括号"><a href="#解题思路1-消去括号" class="headerlink" title="解题思路1 消去括号"></a>解题思路1 消去括号</h5><p>看清题后，发现题目要求只是做加减法因此可以快速消去括号。用栈来记录去掉括号后的符号变化，用一个指针表示当前位置处的符号。即扫描一遍字符串，遇到空格则略过，遇到+或-更新指针，遇到(添加栈顶符号，遇到)弹出栈顶符号。</p>
<p>代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">calculate</span>(<span class="params">self, s: <span class="built_in">str</span></span>) -&gt; int:</span></span><br><span class="line">        <span class="comment"># 扫描字符，遇到+或-时更新栈顶符号，遇到（或)时也更新栈顶符号</span></span><br><span class="line">        ops = [<span class="number">1</span>]</span><br><span class="line">        sign = <span class="number">1</span></span><br><span class="line">        res = <span class="number">0</span></span><br><span class="line">        i = <span class="number">0</span></span><br><span class="line">        <span class="keyword">while</span> i &lt; <span class="built_in">len</span>(s):</span><br><span class="line">            <span class="keyword">if</span> s[i] == <span class="string">&quot; &quot;</span>:</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">            <span class="keyword">elif</span> s[i] == <span class="string">&quot;(&quot;</span>:</span><br><span class="line">                ops.insert(<span class="number">0</span>, sign)</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">            <span class="keyword">elif</span> s[i] == <span class="string">&quot;)&quot;</span>:</span><br><span class="line">                ops.pop(<span class="number">0</span>)</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">            <span class="keyword">elif</span> s[i] == <span class="string">&quot;+&quot;</span>:</span><br><span class="line">                sign = ops[<span class="number">0</span>]</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">            <span class="keyword">elif</span> s[i] == <span class="string">&quot;-&quot;</span>:</span><br><span class="line">                sign = -ops[<span class="number">0</span>]</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                num = <span class="number">0</span></span><br><span class="line">                <span class="keyword">while</span> i &lt; <span class="built_in">len</span>(s) <span class="keyword">and</span> s[i].isdigit():</span><br><span class="line">                    num = num*<span class="number">10</span> + <span class="built_in">int</span>(s[i])</span><br><span class="line">                    i += <span class="number">1</span></span><br><span class="line">                res += sign * num</span><br><span class="line">        <span class="keyword">return</span> res</span><br></pre></td></tr></table></figure>

<h5 id="踩坑记录二-判断字符是否为数字"><a href="#踩坑记录二-判断字符是否为数字" class="headerlink" title="踩坑记录二 判断字符是否为数字"></a>踩坑记录二 判断字符是否为数字</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> i &lt; <span class="built_in">len</span>(s) <span class="keyword">and</span> s[i].isdigit():</span><br></pre></td></tr></table></figure>

<p>这句话中，用到<code>isdigit()</code>这个判断方法，不能直接用<code>int(s[i])</code>否则会报错</p>
<h5 id="踩坑记录三-循环时用while循环而不是for循环"><a href="#踩坑记录三-循环时用while循环而不是for循环" class="headerlink" title="踩坑记录三 循环时用while循环而不是for循环"></a>踩坑记录三 循环时用<code>while</code>循环而不是<code>for</code>循环</h5><p>在遍历整个字符串时，如果采用<code>for</code>循环则会这样：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(s)):</span><br><span class="line">	i +=<span class="number">1</span></span><br></pre></td></tr></table></figure>

<p>如果在循环内多次出现<code>i+=1</code>时，下一次循环还是会从上一个循环的i加上1之后开始，并不会因为循环内的i值改变而变化，因此这里需要使用while循环。</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://example.com/2021/03/13/224.%E5%9F%BA%E6%9C%AC%E8%AE%A1%E7%AE%97%E5%99%A8/" data-id="ckm7t5pcc0000hott4dzwhooy" data-title="基本计算器" class="article-share-link">Share</a>
      
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag">学习笔记</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
  
    <a href="/2021/03/13/django%E8%87%AA%E5%AE%9A%E4%B9%89%E6%97%A5%E5%BF%97/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">django自定义日志</div>
    </a>
  
</nav>

  
</article>


</section>
        
          <aside id="sidebar">
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Categories</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/SCIP/">SCIP</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/django/">django</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/leetcode/">leetcode</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/oracle/">oracle</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag">学习笔记</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" style="font-size: 10px;">学习笔记</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/03/">March 2021</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2021/03/13/224.%E5%9F%BA%E6%9C%AC%E8%AE%A1%E7%AE%97%E5%99%A8/">基本计算器</a>
          </li>
        
          <li>
            <a href="/2021/03/13/django%E8%87%AA%E5%AE%9A%E4%B9%89%E6%97%A5%E5%BF%97/">django自定义日志</a>
          </li>
        
          <li>
            <a href="/2021/03/13/sqlldr%E5%AF%BC%E5%85%A5%E5%A4%A7%E9%87%8F%E6%95%B0%E6%8D%AE%E5%88%B0oracle%E6%95%B0%E6%8D%AE%E5%BA%93/">使用sqlldr导入上亿条数据到oracle中</a>
          </li>
        
          <li>
            <a href="/2021/03/13/windows%E7%8E%AF%E5%A2%83%E4%B8%8B%E5%AE%89%E8%A3%85pyscipopt/">windows下安装pyscipopy</a>
          </li>
        
          <li>
            <a href="/2021/03/13/hello-world/">Hello World</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      
      &copy; 2021 John Doe<br>
      Powered by <a href="https://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="/js/jquery-3.4.1.min.js"></script>



  
<script src="/fancybox/jquery.fancybox.min.js"></script>




<script src="/js/script.js"></script>





  </div>
</body>
</html>